package org.zjx.command.entity;

import lombok.Data;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

@Data
public class WordBean {
    private String name;
    private Rect rect;
    private int type;
    private int[][] block;

    public WordBean(Rect rect, int[][] block) {
        this.rect = rect;
        this.block = block;
    }


    // 获取矩形的 top 值
    public int getTop() {
        return rect.getTop();
    }

    // 获取矩形的 bottom 值
    public int getBottom() {
        return rect.getBottom();
    }

    // 获取矩形的 left 值
    public int getLeft() {
        return rect.getLeft();
    }

    // 获取矩形的 right 值
    public int getRight() {
        return rect.getRight();
    }

    // 获取矩形的 height
    public int getHeight() {
        return rect.getBottom() - rect.getTop() + 1;
    }

    public int getWith() {
        return rect.getRight() - rect.getLeft() + 1;
    }


    // 排序函数：按 top 值排序
    public static class WordBeanComparator implements Comparator<WordBean> {
        @Override
        public int compare(WordBean w1, WordBean w2) {
            return Integer.compare(w1.getTop(), w2.getTop());
        }
    }



    // 合并行内的字体
    public static List<List<WordBean>> mergeWordsIntoLines(List<WordBean> wordBeans) {
        // 按 top 值排序
        wordBeans.sort(new WordBeanComparator());

        List<List<WordBean>> lines = new ArrayList<>();
        List<WordBean> currentLine = new ArrayList<>();

        // 定义一个阈值，表示在同一行内的字的 top 值差异
        final int lineThreshold = 5;

        // 遍历排序后的 wordBeans，将它们按行分组
        for (WordBean bean : wordBeans) {
            if (currentLine.isEmpty()) {
                currentLine.add(bean);
            } else {
                WordBean lastBeanInLine = currentLine.get(currentLine.size() - 1);
                if (Math.abs(lastBeanInLine.getTop() - bean.getTop()) < lineThreshold) {
                    currentLine.add(bean);
                } else {
                    lines.add(currentLine);
                    currentLine = new ArrayList<>();
                    currentLine.add(bean);
                }
            }
        }

        if (!currentLine.isEmpty()) {
            lines.add(currentLine);
        }

        return lines;
    }


}
